﻿using System.Collections.Generic;
using Framework;
using UnityEngine;
using UnityEngine.ResourceManagement.ResourceProviders;

namespace Game
{
    public class SceneSystem : EventTargetSingleton<SceneSystem>
    {
        private Dictionary<string, SceneEntity> _name2entityDict = new Dictionary<string, SceneEntity>();

        private SceneEntity _activeScene;
        
        public void LoadScene(string sceneName)
        {
            SceneConfigData sceneData = ConfigSystem.Instance.Get<SceneConfigEntity>().GetData(sceneName);
            SceneBTreeContext sceneContext = new SceneBTreeContext();
            sceneContext.sceneData = sceneData;
            BTreeBuilder<SceneBTreeContext> loadSceneBTreeBuilder = new BTreeBuilder<SceneBTreeContext>(sceneContext);
            loadSceneBTreeBuilder.Sequence();
            loadSceneBTreeBuilder.Actionable(new LoadSceneActionable());
            loadSceneBTreeBuilder.EndComposite();

            BehaviorTree<SceneBTreeContext> loadSceneBTree = loadSceneBTreeBuilder.Build();
            loadSceneBTree.Ended += OnLoadSceneCompleted;
            BTreeScheduler.Instance.StartTree(loadSceneBTree);
        }

        public SceneEntity CreateScene(SceneInstance sceneInstance, SceneConfigData sceneData)
        {
            SceneEntity sceneEntity = new SceneEntity(sceneInstance, sceneData);
            _name2entityDict.Add(sceneEntity.name, sceneEntity);
            return sceneEntity;
        }

        public void SetSceneActive(string sceneName, bool isActive)
        {
            _activeScene = _name2entityDict[sceneName];
            _activeScene.SetActive(isActive);
        }
        
        private void OnLoadSceneCompleted(SceneBTreeContext sceneContext)
        {
        }
    }
}